package com.hgc.ch02.semaphore;

import java.sql.Connection;
import java.util.LinkedList;
import java.util.concurrent.Semaphore;

/**
 * Created by 01367627 on 2019/7/8.
 */
public class DBPoolSemaphore {
    private static LinkedList<Connection> pool = new LinkedList();
    private final Semaphore useful, useless;

    public DBPoolSemaphore(int initialSize) {
        if (initialSize <= 0) {
            throw new IllegalArgumentException("initialSize 必须大于0");
        }
        for (int i = 0; i < initialSize; i++) {
            pool.addLast(SqlConnectionImpl.fetchConneciont());
        }
        useful = new Semaphore(initialSize);
        useless = new Semaphore(0);
    }

    public Connection fetchConnecion() throws InterruptedException {
        useful.acquire();
        Connection connection;
        synchronized (pool) {
            connection = pool.removeFirst();
        }
        useless.release();
        return connection;
    }

    public void releaseConnection(Connection connection) throws InterruptedException {
        if (connection != null) {
            System.out.println("当前有" + useful.getQueueLength() + "个线程在等待连接!当前可用连接数：" + useful.availablePermits());
            useless.acquire();
            synchronized (pool){
                pool.addLast(connection);
            }
            useful.release();
        }
    }

}
